/*
 * Copyright (C) 2007 BitLab.com.ua
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ua.com.bitlab.rsprocessor;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Yaroslav Yermak
 * @version 1.0, Mar 7, 2007
 */
public abstract class BaseRsProcessor<T> implements RsProcessor {
// ------------------------------ FIELDS ------------------------------

    private Object currentObject;

// -------------------------- OTHER METHODS --------------------------

    public  T currentObject(){
        return (T) currentObject;
    }

    protected boolean init(Class clazz, Object primaryKey, Chain chain) throws SQLException {
        if (currentObject != null) {
            if (!ReflectionHelper.isPrimaryKeySet(currentObject)) {
                ReflectionHelper.setPrimaryKey(currentObject, primaryKey);
            }
            return false;
        }

        Map<Class, Map<Integer, Object>> cache = chain.getCache();

        if (!cache.containsKey(clazz)) {
            cache.put(clazz, new HashMap<Integer, Object>());
        }

        Map cachePerClass = cache.get(clazz);

        if (cachePerClass.containsKey(primaryKey)) {
            currentObject = cachePerClass.get(primaryKey);
            return false;
        }

        try {
            Object o = clazz.getConstructor().newInstance();
            ReflectionHelper.setPrimaryKey(o, primaryKey);
            currentObject = o;
            cachePerClass.put(primaryKey, currentObject);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
